<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDailog=true">添加角色</el-button>
      </div>
      <el-table v-loading="isLoading" :data="list">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" placeholder="输入角色" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用状态">
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              :active-value="1"
              :inactive-value="0"
              active-text="是"
              inactive-text="否"
            />
            <span v-else>{{ row.state ? '已启用' : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="texteare" row="1" placeholder="输入描述" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="editOk(row)">确定</el-button>
              <el-button size="mini" @click="editCancel(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEdit(row)">编辑权限</el-button>
              <el-popconfirm
                :title="`是否删除${row.name}角色`"
                style="margin-left:8px"
                @onConfirm="btnDel(row.id)"
              >
                <el-button slot="reference" size="mini" type="text">删除权限</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:60px" align="middel" justify="end">
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :current-page="pageParams.page"
          :page-size="pageParams.pageSize"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog width="500px" label-width="120px" :visible.sync="showDailog" title="新增角色" @close="btnCancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" size="mini" style="width:390px" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch
            v-model="roleForm.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :row="3" style="width:390px" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="8">
              <el-button size="mini" type="primary" @click="btnOk">确认</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限弹窗 -->
    <el-dialog :visible.sync="showPermission" title="分配权限">
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col>
          <el-button size="mini" type="primary" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermission = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, addRole, editRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { ListToTree } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1,
        pagesize: 8,
        total: 0
      },
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blue' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'change' }
        ]
      },
      isLoading: false,
      showDailog: false,
      showPermission: false,
      permissionData: [],
      currentRoleID: null,
      permIds: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取角色列表
    async getList() {
      this.isLoading = true
      const result = await getRoleList(this.pageParams)
      this.list = result.rows
      this.pageParams.total = result.total
      this.list.forEach(item => {
        // 添加一个响应式属性
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', { name: item.name, state: item.state, description: item.description })
      })
      this.isLoading = false
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getList()
    },
    btnOk() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getList()
          // 重置表单
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields()
      this.showDailog = false
    },
    // 添加角色
    addRole() {
      // todo
    },
    btnEdit(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 取消编辑
    editCancel(row) {
      row.isEdit = false
    },
    // 编辑确认
    async editOk(row) {
      if (row.editRow.name && row.editRow.description) {
        await editRole({ ...row.editRow, id: row.id })
        this.$message.success('数据更新成功')
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async btnDel(id) {
      await delRole(id)
      this.$message.success('删除成功')
      if (this.list.length === 1) {
        // 删除的是最后一条[前端]
        this.pageParams.page--
      }
      this.getList()
    },
    // 分配权限按钮
    async btnPermission(id) {
      const result = ListToTree(await getPermissionList(), 0)
      this.permissionData = result
      this.currentRoleID = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.showPermission = true
    },
    // 确定分配按钮
    async btnPermissionOK() {
      await assignPerm({ id: this.currentRoleID, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('角色分配成功')
      this.showPermission = false
    }
  }
}
</script>

<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
</style>
